package com.suoluo.zenapp.controllers;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;

import com.google.gson.Gson;

public class JSONInterceptor extends ControllerInterceptorAdapter {

	/**
	 * 覆盖这个方法，表示只有标注@JSON的控制器或方法才会被此拦截器拦截
	 */
	@Override
	public Class<? extends Annotation> getRequiredAnnotationClass() {
		return JSON.class;
	}

	@Override
	protected Object after(Invocation inv, Object instruction) throws Exception {

		// 转码成json
		encodeToJSON(inv, instruction);
		// 返回空串给Rose，让其不用再管render的事情了
		return "";

	}
	private void encodeToJSON(Invocation invocation, Object encodeObj)
			throws IOException {
		HttpServletResponse response = invocation.getResponse();
		if (response.getContentType() == null) {
			response.setContentType("application/json;charset=UTF-8");
		}
		Gson gson = new Gson();

		String json = gson.toJson(encodeObj);
		response.getWriter().write(json);
	}

	@Override
	public void afterCompletion(Invocation inv, Throwable ex) throws Exception {
//		{=图片保存失败, $$paoding-rose.model=net.paoding.rose.web.var.ModelImpl@193ee6b, $$paoding-rose.invocation=/zenapp/admin/dest/saveDest, javax.servlet.error.status_code=200, org.springframework.web.servlet.support.RequestContext.CONTEXT=WebApplicationContext for namespace 'context@controllers.admin.dest', javax.servlet.error.exception=com.suoluo.zenapp.service.ServiceException: 图片保存失败, javax.servlet.error.request_uri=/zenapp/admin/dest/saveDest}
		inv.getRequest().removeAttribute("javax.servlet.error.exception_type");
		inv.getRequest().removeAttribute("javax.servlet.error.message");
		inv.getRequest().removeAttribute("javax.servlet.error.exception");
		
	}
	@Inherited
	@Target({ ElementType.TYPE, ElementType.METHOD })
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	public @interface JSON {

	}
}
